package luke4fun.wheresmymoney.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import luke4fun.wheresmymoney.domain.Category;

public class CategoryDAO {
	private static CategoryDAO instance = null;
	
	private CategoryDAO(){}
	
	public static CategoryDAO getInstance() {
		if (instance == null) {
			instance = new CategoryDAO();
		}
		return instance;
	}
	
	/**
	 * query categories
	 * @param db
	 * @param category
	 * @return
	 */
	public List<Category> queryCategory(SQLiteDatabase db, String category) {
		List<Category> list = new ArrayList<Category>(0);
		Cursor cursor;
		if (category == null) {
			cursor = db.query(DBConstants.TABLE_CATEGORY, 
								null, 
								null,
								null, 
								null, 
								null, 
								DBConstants.CATEGORY_FREQUENCE + " DESC, " +
								DBConstants.CATEGORY_ID + " DESC");
		}
		else {
			cursor = db.query(DBConstants.TABLE_CATEGORY, 
								null, 
								DBConstants.CATEGORY_NAME + "=?",
								new String[] { category }, 
								null, 
								null, 
								DBConstants.CATEGORY_FREQUENCE + " DESC, " +
								DBConstants.CATEGORY_ID + " DESC");
		}
		
		while(cursor.moveToNext()) {
			Category bean = new Category();
			bean.setId(cursor.getLong(cursor.getColumnIndex(DBConstants.CATEGORY_ID)));
			bean.setName(cursor.getString(cursor.getColumnIndex(DBConstants.CATEGORY_NAME)));
			bean.setColor(cursor.getInt(cursor.getColumnIndex(DBConstants.CATEGORY_COLOR)));
			bean.setFrequence(cursor.getLong(cursor.getColumnIndex(DBConstants.CATEGORY_FREQUENCE)));
			
			list.add(bean);
		}
		
		return list;
	}
	
	/**
	 * insert one category into category table
	 * @param db
	 * @param cv
	 * @return
	 */
	public boolean insertCategory(SQLiteDatabase db, ContentValues cv) {
		long id = db.insert(DBConstants.TABLE_CATEGORY, null, cv);
		return id == -1 ? false : true;
	}
	
	/**
	 * delete one category from category table
	 * @param db
	 * @param id
	 * @return
	 */
	public boolean deleteCategory(SQLiteDatabase db, long id) {
		try {
			db.delete(DBConstants.TABLE_CATEGORY, DBConstants.CATEGORY_ID + "=?", new String[] {id + ""});
			return true;
		} catch (Exception e) {
			Log.e("del category", e.getMessage());
		}
		return false;
	}
}
